<template>
  <el-dialog :close-on-click-modal="false" class="yy-modal--custom pc-temp-model" width="800px" v-model="isVisible" @close="onCancelModel" append-to-body>
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">文件上传</h4>
    </template>
    <div class="pc-temp-model_content">
      <div class="pc-temp-model_content-upload">
        <el-upload
            ref="uploadRef"
            class="pc-temp-model—-upload"
            :headers="upload.headers"
            multiple
            :limit="templateUploadTotalCount"
            :action="getUploadUrl"
            drag
            accept=".jpeg,.jpg,.png,.svg,.webp,.mp4,.wmv,.avi,.ppt,.pptx,.doc,.docx,.txt,.pdf,.xls,.xlsx"
            :auto-upload="false"
            :show-file-list="false"
            :on-progress="onProgress"
            :on-change="onFileUpload"
        >
          <el-icon class="el-icon--upload"><IconUploadFilled /></el-icon>
          <div class="el-upload__text">
            拖拽上传或 <em>点击上传</em>
          </div>
        </el-upload>
      </div>

      <div class="pc-temp-model_content-files">
        <el-table :data="files"  style="width: 100%">
          <el-table-column prop="aliasName" label="文件名称" >
            <template #default="scope">
              <el-input v-model="scope.row.aliasName" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="文件说明" >
            <template #default="scope">
              <el-input v-model="scope.row.description" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="文件大小" width="100">
            <template #default="scope">
              <span>{{formatFileSizeLabel(scope.row.size)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
             <div style="display: flex; align-items: center;">
               {{getUploadLabel(scope.row.status)}}
               <span v-if="scope.row.errorMsg" style="color: var(--el-color-danger);">
                 <el-tooltip
                     effect="dark"
                     :content="scope.row.errorMsg"
                     placement="top"
                 >
                    <el-icon><WarningFilled /></el-icon>
                 </el-tooltip>
              </span>
             </div>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作" width="100" align="center">
            <template #default="scope">
              <el-link :underline="false" style="margin: 0 5px; font-size: 20px;" @click="onRemoveFile(scope.row)">
                <el-icon><IconClose /></el-icon>
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
        <div style="color: #666;">一次最多允许上传
          <span>{{ templateUploadTotalCount }}</span> 个文件，还可以添加
          <span style="color: red;">{{uploadFileCount}}</span> 个</div>
        <div>
           <el-button @click="onCancelModel">关闭</el-button>
           <el-button type="primary" @click="submitUpload">保存</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {Close as IconClose, UploadFilled as IconUploadFilled, WarningFilled} from "@element-plus/icons-vue"
import {defineEmits, defineExpose, onBeforeMount, reactive, ref, computed} from "vue"
import {
  ElButton,
  ElDialog,
  ElIcon,
  ElInput, ElLink,
  ElMessage,
  ElTable,
  ElTableColumn, ElTooltip,
  ElUpload,
  UploadFile,
  UploadFiles
} from "element-plus"
import {formatFileSize} from "@/utils/yayi";
import {ResourceModel} from "@/model/ResourceModel";
import ResourceApi from "@/api/broadcast/resource";
import StorageUtils from '@/utils/StorageUtils'
import {EnvConfig} from "@/utils";


const $emit = defineEmits({
  batchSaveFile: (temps: ResourceModel[]) => temps
})
const templateUploadTotalCount = 10
const currentDeptId =  ref('')
const props = defineProps({
    folderId: {
        type: String,
        required: true,
        default: null
    }
})
const upload = reactive({
  headers: {
    'Authorization': "Bearer " + StorageUtils.getUserLoginToken()
  },
  url: EnvConfig.baseApi + '/broadcast/resource/file/upload'
})

const getUploadUrl = computed(() => {
    let url = upload.url
    if (currentDeptId.value) {
      url += '?deptId=' + currentDeptId.value
    }
    if (props.folderId) {
      if (url.lastIndexOf("?") >= 0) {
        url += '&folderId='+props.folderId
      } else {
        url += '?folderId='+props.folderId
      }
    }
    return url
})

const uploadRef = ref()
// 文件列表,显示在ui上
const files = ref([])
// 上传控件的文件列表，不显示在ui
let uploadFileArr = []


const isVisible = ref(false)
const isSaving = ref(false)

const uploadFileCount = computed(() => {
  const hasCount =  files.value.filter(item => item.status != 'success').length
  return templateUploadTotalCount - hasCount
})


const getUploadLabel = (uploadStatus: string) => {
  const statusMap = {
    'ready': '待上传',
    'uploading': '上传中',
    'success': '上传成功',
    'fail': '上传失败'
  }
  return statusMap[uploadStatus]
}
const onProgress = (event: Event,uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  uploadFileArr = uploadFiles
  // uploading
  const index = files.value.findIndex(item => item.uid === uploadFile.uid)
  if (index >= 0) {
    files.value.splice(index, 1, Object.assign(files.value[index], {status: uploadFile.status, percentage: uploadFile.percentage}))
  }
}

const onRemoveFile = (file: UploadFile) => {

  // 从上传列表中移除
  const exitIndex = uploadFileArr.findIndex(item => item.uid === file.uid)
  exitIndex >= 0 && uploadFileArr.splice(exitIndex, 1)

  const index = files.value.findIndex(item => item.uid === file.uid)
  // 从页面显示列表移除
  if (index >= 0) {
    // 如果删除的是上传图片成功，但是保存不成功的，需要删除上传的文件
    if (!!files.value[index].filePath && !files.value[index].fileId) {
      ResourceApi.deleteTempByFilePath([files.value[index].filePath])
    }
    files.value.splice(index, 1)
  }

}

const onFileUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  isSaving.value = true
  uploadFileArr = uploadFiles
  if (uploadFile.status === 'ready') {
    files.value.push(Object.assign({}, uploadFile, {
      aliasName: uploadFile.name.substring(0, uploadFile.name.indexOf('.')),
      description: ''
    }))
  } else {
    const response: any = uploadFile.response
    const index = files.value.findIndex(item => item.uid === uploadFile.uid)
    let status = uploadFile.status;
    // 如果没有获取到上传的文件地址，则标记为失败
    if (status === 'success' && !response.data) {
      status = 'fail'
    }
    index >= 0 && files.value.splice(index, 1, Object.assign(files.value[index],
        {
          status:status,
          percentage: uploadFile.percentage,
          filePath: uploadFile.status === 'success' ? response.data.resPath : null,
          resId: uploadFile.status === 'success' ? response.data.resId : null,
          errorMsg: status === 'success' ? null : response.message,
          ...response.data
        }))

    saveTempList()
  }
}

const saveTempList = () => {
  const successCount = files.value.filter(item => item.status === 'success').length
  // 全部上传完成，则走提交保存接口
  if (files.value.length == successCount) {
    console.log('----------save file list-----------', files.value)
    $emit('batchSaveFile', files.value.map(item => new ResourceModel().deserialize(item)))
    isSaving.value = false
    onCancelModel()
    // isSaving.value = true
    // const saveFileList = files.value.map(item => !item.fileId && item.status === 'success' && item);

    // ResourceApi.batchSave(props.folderId, saveFileList.map(item => new ResourceModel().deserialize({
    //   resName: item.aliasName,
    //   description: item.description,
    //   resPath: item.filePath,
    //   fileSize: item.size
    // }))).then((res) => {
    //   $emit('batchSaveFile', res)
    //   files.value.forEach(item => {
    //     const resItem = res.find(r => r.resPath.endsWith(item.filePath))
    //     if (resItem) {
    //       Object.assign(item, {fileId: resItem.resId})
    //     }
    //   })
    //   isSaving.value = false
    //   onCancelModel()
    // }, (error) => {
    //   isSaving.value = false
    // })
  }
}

const formatFileSizeLabel = (fizeSize: number) => {
  return formatFileSize(fizeSize)
}

const onShowModel = (deptId: string) => {
  console.log('--------------------------------', deptId)
  currentDeptId.value = deptId
  isVisible.value = true
}

const onCancelModel = () => {
  isVisible.value = false
  files.value = []
  uploadFileArr = []
  uploadRef.value.clearFiles()
}

const submitUpload = () => {
  if (files.value.length > 0) {
    if (files.value.filter(item => !item.aliasName)?.length) {
      ElMessage({
        type: 'warning',
        message: '文件名称不能为空!',
        showClose: true
      })
      return
    }
    if (files.value.filter(item => item.status != 'success').length) {
      files.value.forEach((file) => {
        if (file.status === 'fail') {
          uploadFileArr.unshift(Object.assign({}, file, {status: 'ready'}))
        }
      })
      uploadRef.value?.submit()
    } else {
      saveTempList()
    }
  }
}

defineExpose({
  onShowModel
})

</script>

<style scoped lang="scss">
  .pc-temp-model {
    &_content {
      padding: 15px;
    }
  }

</style>
<style lang="scss">
.pc-temp-model—-upload {
  .el-upload-dragger {
    padding: 5px!important;
    .el-icon--upload {
      font-size: 45px;
      margin-bottom: 0px;
    }
  }
}
</style>
